package com.atguigu.gulimail.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SkuStock;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.product.entity.*;
import com.atguigu.gulimail.product.feign.CouponFeignService;
import com.atguigu.gulimail.product.feign.SearchFeignService;
import com.atguigu.gulimail.product.feign.WareFeignService;
import com.atguigu.gulimail.product.service.*;
import com.atguigu.gulimail.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService infoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuVoInfo(SpuSaveVo spuSaveVo) {
        //1、首先保存spu的基本信息 `pms_spu_info`
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuInfo(spuInfoEntity);
        //保存之后，就可以获得id

        //2、保存spu的一些描述 `pms_spu_info`
        Long spuId = spuInfoEntity.getId();
        List<String> decript = spuSaveVo.getDecript();
        infoDescService.saveSpuInfoDesrc(spuId, decript);

        // 3、spu的图片信息pms_spu_images
        List<String> images = spuSaveVo.getImages();
        imagesService.saveImages(spuId, images);

        //4、spu 规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setAttrId(item.getAttrId());
            AttrEntity byId = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            return productAttrValueEntity;

        }).collect(Collectors.toList());

        productAttrValueService.saveBatch(collect);

        //5、spu的积分信息 跨库 gulimail_sms ==》sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        R save = couponFeignService.save(spuBoundsTo);
        if (save.getCode() != 0) {
            log.error("保存积分信息失败");
        }

        //5.sku的基本信息 pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {

                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                /**
                 *     private String skuName;
                 *     private BigDecimal price;
                 *     private String skuTitle;
                 *     private String skuSubtitle;
                 */
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
                skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);
                //保存之后 就能获得skuinfo 的Id
                Long skuId = skuInfoEntity.getSkuId();

                //sku图片信息 pms_sku_images
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(image -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    imagesEntity.setImgUrl(image.getImgUrl());
                    imagesEntity.setDefaultImg(image.getDefaultImg());
                    return imagesEntity;
                }).filter(fi -> {
                    //如果为空，那么就过滤掉。如果不为空。那么就保留。
                    return !StringUtils.isEmpty(fi.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
                List<Attr> attr = item.getAttr();
                //sku销售属性信息 pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(itme -> {

                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(itme, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //sku的满减信息 跨库 gulimail_sms==》 sms_sku_full_reduction\sms_sku_ladder\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //BigDecimal 必须要用compartTo方法来做比较 返回值-1，0,1 就是小于 等于 大于
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                    R r = couponFeignService.saveInfo(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("保存满减信息失败");
                    }
                }


            });
        }
    }

    @Override
    public void saveSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    @Override
    public PageUtils queryByConditions(Map<String, Object> params) {

        /**
         *    key: '华为',//检索关键字
         *    catelogId: 6,//三级分类id
         *    brandId: 1,//品牌id
         *    status: 0,//商品状态
         */
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && Integer.parseInt(catelogId) != 0) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && Integer.parseInt(brandId) != 0) {
            queryWrapper.eq("brand_id", brandId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status) && Integer.parseInt(status) != 0) {
            queryWrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //这些sku的属性都是一样的 查一遍就行了
        //TODO 查询sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> productAttrValueEntityList = attrService.getAttrValuesBySpuId(spuId);
        List<Long> attrIds = productAttrValueEntityList.stream().map(m -> {
            return m.getAttrId();
        }).collect(Collectors.toList());
        //找到所有可以被检索的
        List<Long> attrids = attrService.getSearched(attrIds);

        Set<Long> idsSet = new HashSet<>(attrids);


        List<SkuEsModel.Attrs> collect = productAttrValueEntityList.stream().filter(f -> {
            return idsSet.contains(f.getAttrId());
        }).map(m -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(m, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //TODO 通过远程调用库存微服务 查询是否有当前sku库存是否为null
        Map<Long, Boolean> stockMap = null;
        try {
            R r = wareFeignService.hasStock(skuIds);

            TypeReference<List<SkuStock>> typeReference = new TypeReference<List<SkuStock>>() {
            };
            List<SkuStock> skuStocks = r.getData(typeReference);
            stockMap = skuStocks.stream().collect(Collectors.toMap(SkuStock::getSkuId, m -> m.isHasStock()));

        } catch (Exception e) {
            log.error("库存服务调用失败:原因，{}", e);
        }


        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModelList = skuInfoEntities.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            //组装需要的数据
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //1、发起远程调用查询库存系统是否有库存
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            //TODO 热度评分
            esModel.setHotScore(0L);

            //2、封装brand数据  和分类数据
            Long brandId = sku.getBrandId();
            BrandEntity brandEntity = brandService.getById(brandId);
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            Long catalogId = sku.getCatalogId();
            CategoryEntity categoryEntity = categoryService.getById(catalogId);
            esModel.setCatalogName(categoryEntity.getName());

            esModel.setAttrs(collect);


            return esModel;
        }).collect(Collectors.toList());


        //  商品上架、
        R r = searchFeignService.productStatusUp(skuEsModelList);

        if (r.getCode() == 0) {
            //如果成功。 修改当前状态  publish_status
            baseMapper.updateStatus(spuId, ProductConstant.ProductStatus.SPU_UP.getCode());
        } else {
            //TODO 重复调用？ 接口幂等性。
        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);

        return spuInfoEntity;
    }

}